package processing_layer;

import java.util.HashMap;

import database_layer.Common;
import database_layer.QueryDispatcher;

/**
 * This class is part of the AJAX searching mini-application. It's part in the
 * foot-chain between the DB and the user. It is used to invoke a specific query
 * to the DB, using a given parameter. 
 */
public class SearchProxy
{
	public static HashMap<String,Course> queryForParameter(String parameter,
			                                               HashMap<String,Integer> currentScores)
	{
		HashMap<String,Course> fetchedCoursesByName = null;
		HashMap<String,Course> fetchedCoursesByDescription = null;
		
		fetchedCoursesByName = QueryDispatcher.findCoursesByParameter(Common.courseNameField, parameter);
		if (null == fetchedCoursesByName)
		{
			return null;
		}
		
		fetchedCoursesByDescription = QueryDispatcher.findCoursesByParameter(Common.descriptionField, parameter);
		if (null == fetchedCoursesByDescription)
		{
			return null;
		}
		
		for (String courseName : fetchedCoursesByName.keySet())
		{
			if (currentScores.containsKey(courseName))
			{
				Integer newScore = currentScores.get(courseName) + Common.NAME_MATCH_SCORE;
				currentScores.remove(courseName);
				currentScores.put(courseName, newScore);
			}
			else
			{
				currentScores.put(courseName, new Integer(Common.NAME_MATCH_SCORE));
			}
		}
		
		for (String courseName : fetchedCoursesByDescription.keySet())
		{
			if (currentScores.containsKey(courseName))
			{
				Integer newScore = currentScores.get(courseName) + Common.DESCRIPTION_MATCH_SCORE;
				currentScores.remove(courseName);
				currentScores.put(courseName, newScore);
			}
			else
			{
				currentScores.put(courseName, new Integer(Common.DESCRIPTION_MATCH_SCORE));
			}
		}
		
		fetchedCoursesByName.putAll(fetchedCoursesByDescription);
		return fetchedCoursesByName;
	}
}
